/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kyakya.User;
import kyakya.manager.DBManager;

/**
 *
 * @author hartono
 */
@WebServlet(name = "Achievement", urlPatterns = {"/Achievement"})
public class Achievement extends HttpServlet {

    public boolean checkAchievement(Statement st, int userID, int achid) {
        String query = "SELECT * from `tbl_achiever` where `user_id` = '" + userID + "' and `achievement_id` = '" + achid + "'";
        try {
            ResultSet results = st.executeQuery(query);
            if (results.next()) {
                return true;
            }
        } catch (SQLException ex) {
            Logger.getLogger(Achievement.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        return false;
    }

    public boolean achieveIt(Statement st, int userID, int achid) {
        String query = "INSERT INTO  `tbl_achiever` values ( " + userID + " , " + achid + "  ) ";
        try {
            int result = st.executeUpdate(query);
            return result != 0;

        } catch (SQLException ex) {
            Logger.getLogger(Achievement.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection mConn = DriverManager.getConnection("jdbc:mysql://localhost/progin_171_13509024", "progin", "progin");
            Statement mStatement = mConn.createStatement();


            StringBuilder sb = new StringBuilder();
            sb.append(" ");
            // cek dapet achievement apa                        
            // posting sekali
            int userID = Integer.parseInt(request.getParameter("id"));
            User user = DBManager.getUserByID(userID);

            if (user.getPostCount() >= 1 && user.getPostCount() < 10) {
                if (checkAchievement(mStatement, userID, 1)) {
                } else {
                    // achieve it
                    achieveIt(mStatement, userID, 1);
                    sb.append("1 ");
                }

            } else {
            }
            // komentar sekali            
            if (user.getCommentCount() >= 1 && user.getCommentCount() < 10) {
                if (checkAchievement(mStatement, userID, 2)) {
                } else {
                    // achieve it                    
                    achieveIt(mStatement, userID, 2);
                    sb.append("2 ");
                }

            } else {
            }
            // posting 10x
            if (user.getPostCount() >= 10 && user.getPostCount() < 50) {
                if (checkAchievement(mStatement, userID, 3)) {
                } else {
                    // achieve it
                    achieveIt(mStatement, userID, 3);
                    sb.append("3 ");
                }

            } else {
            }
            // komentar 20x
            if (user.getCommentCount() >= 20 && user.getCommentCount() < 100) {
                if (checkAchievement(mStatement, userID, 4)) {
                } else {
                    // achieve it                    
                    achieveIt(mStatement, userID, 4);
                    sb.append("4 ");
                }

            } else {
            }
            // like 100
            String query = "";
            ResultSet res = null;

            if (checkAchievement(mStatement, userID, 5)) {
            } else {
                try {
                    query = "SELECT max(`count`) as `max`FROM (SELECT `post_id`, count(`post_id`) as`count`  FROM `tbl_like` WHERE `post_id` in (SELECT `id` FROM `tbl_post` WHERE `author_id` = " + userID + " ) group by `post_id` ) as `table_count_post`";
                    res = mStatement.executeQuery(query);
                    if (res != null) {
                        if (res.next()) {
                            int maxlike = res.getInt("max");
                            if (maxlike >= 100) {
                                achieveIt(mStatement, userID, 5);
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }
            // dislike 100
            if (checkAchievement(mStatement, userID, 6)) {
            } else {
                try {
                    query = "SELECT max(`count`) as `max`FROM (SELECT `post_id`, count(`post_id`) as`count`  FROM `tbl_like` WHERE `post_id` in (SELECT `id` FROM `tbl_post` WHERE `author_id` = " + userID
                            + " ) group by `post_id` ) as `table_count_post`";
                    res = mStatement.executeQuery(query);
                    if (res != null) {
                        if (res.next()) {
                            int maxdislike = res.getInt("max");
                            if (maxdislike >= 100) {
                                achieveIt(mStatement, userID, 6);
                            }
                        }
                    }
                } catch (Exception e) {
                }
            }

            // cek uda pernah dapet achievement itu
            // tandain
            // output message            
            out.println(sb.toString());
            mStatement.close();
            mConn.close();
        } catch (Exception ex) {
            Logger.getLogger(Achievement.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Achievement</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Achievement at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
